package org.jeecg.modules.biz.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.biz.auth.entity.AuthInfo;
import org.jeecg.modules.biz.auth.entity.AuthVo;
import org.jeecg.modules.biz.auth.mapper.AuthMapper;
import org.jeecg.modules.biz.auth.service.IAuthService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: 认证信息
 * @Author: Liangyt
 * @Date: 2022-02-28
 * @Version: V1.0
 */
@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, AuthInfo> implements IAuthService {

    @Autowired
    private ISysUserService sysUserService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AuthInfo addOrEdit(AuthVo vo) {
        AuthInfo authInfo = new AuthInfo();
        BeanUtils.copyProperties(vo, authInfo);
        authInfo.setState(0);
        authInfo.setStateInfo("");

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        authInfo.setAuthUserId(sysUser.getId());
        authInfo.setAuthUserName(sysUser.getRealname());

        if (StringUtils.isEmpty(authInfo.getId())) {
            this.save(authInfo);
        } else {
            this.updateById(authInfo);
        }
        return this.getById(authInfo.getId());
    }

    @Override
    public AuthInfo queryAuthByLoginUser() {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<AuthInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuthInfo::getCreateBy, loginUser.getId());
        return this.getOne(wrapper);
    }

    @Override
    public AuthInfo queryAuthByUserId(String userId) {
        LambdaQueryWrapper<AuthInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuthInfo::getAuthUserId, userId);
        return this.getOne(wrapper);
    }
}
